package com.ease.document.flyingsaucer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.ease.document.freemarker.FreeMarkerUtil;
import com.lowagie.text.pdf.BaseFont;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 报告测试
 * 
 */
public class ReportSampleAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -883965605503402738L;

	private InputStream inputStream;

	private String fileName;

	public String export() {
		fileName = "导出中文.pdf";

		try {
			String content = prepareContent();
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ITextRenderer renderer = new ITextRenderer();
			renderer.setDocumentFromString(content);

			ITextFontResolver fontResolver = renderer.getFontResolver();
			fontResolver.addFont("c:/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			renderer.getSharedContext().setUserAgentCallback(new HttpUrlUserAgent(renderer.getOutputDevice()));
			renderer.layout();
			renderer.createPDF(outputStream, true);
			this.inputStream = new ByteArrayInputStream(outputStream.toByteArray());
			outputStream.close();
		} catch (Exception e) {
			// logger.error(e);
			// throw new CommException("export error", e);
		}
		return "export";
	}

	public String prepareContent() {
		// String ftlDir = ServletActionContext.getServletContext().getRealPath("/ftl/report");
		// Configuration cfg = new Configuration();
		// cfg.setDefaultEncoding("UTF-8");
		// cfg.setDirectoryForTemplateLoading(new File(ftlDir));
		// cfg.setObjectWrapper(new DefaultObjectWrapper());
		//
		// Template template = cfg.getTemplate("reportSample.freemarker.ftl");
		// ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// OutputStreamWriter osw = new OutputStreamWriter(baos);
		// template.process(this, osw);
		// osw.flush();
		// osw.close();
		Object object = this;
		return FreeMarkerUtil.processFile(ReportSampleAction.class, "reportSample.freemarker.ftl", object);

	}

	/**
	 * @return the inputStream
	 */
	public InputStream getInputStream() {
		return inputStream;
	}

	/**
	 * @param inputStream
	 *            the inputStream to set
	 */
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	/**
	 * @return the fileName
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * @param fileName
	 *            the fileName to set
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
